<template>
  <!-- 顶部选择人员预览 -->
  <div class="dept-people-select-font-size">
    已选: {{ dynamicTags.size }}名人员
  </div>
  <div class="dept-people-select-tag-box">
    <div>
      <el-tag
        v-for="tag in dynamicTags"
        :key="tag"
        :disable-transitions="true"
        class="dept-people-select-tag-item"
      >
        {{ getTagLabel(tag[1]) }}
      </el-tag>
    </div>
  </div>
  <el-row :gutter="22">
    <!-- 部门筛选 -->
    <el-col
      :span="6"
      class="dept-people-select-left-box dept-people-select-overflow"
    >
      <el-input
        v-model="deptSelectModel"
        placeholder="请选择部门"
        :suffix-icon="Search"
        clearable
        @input="filterDept"
        @clear="deptSelectClear"
      />

      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        class="filter-tree"
        :data="deptSelectArr"
        :props="defaultProps"
        :filter-node-method="filterNode"
        @node-click="getTreeKey"
      />
    </el-col>
    <el-col :span="18" class="dept-people-select-table">
      <el-input
        v-model.lazy="queryParams.loginName"
        placeholder="请输入姓名"
        :suffix-icon="Search"
        clearable
        @input="filterInputData"
        @clear="filterInputData"
      ></el-input>
      <jmash-table
        ref="multipleTableRef"
        class="table-top"
        row-key="userId"
        :list-loading="listLoading"
        :data="tableData"
        :table-label="tableLabel"
        @selection-change="tableSelected"
      />

      <jmash-pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:current-page="queryParams.curPage"
        v-model:page-size="queryParams.pageSize"
        class="table-top"
        @pagination="getUserList"
      />
    </el-col>
  </el-row>
</template>
<script setup lang="ts">
import type { PropType, Ref } from "vue";
import { onBeforeMount, ref } from "vue";
import { type ElTree, ElTable } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { type TableColumn } from "jmash-core";
import { deptApi } from "@/api/system/dept/index";
import type { DeptModel } from "@/api/system/dept/types";
import type { UserModel, UserReq } from "@/api/system/user/types";
import { userApi } from "@/api/system/user/index";
import { userLogUser } from "@/api/system/userLog/index";
import type {
  DeptTreeSelectModel,
} from "@/api/system/dept/types";

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const props = defineProps({
  userListArr: {
    type: Map as PropType<Map<string, UserModel>>,
    default: () => [],
  },
  userId: {
    type: Array,
    default: () => [],
  }
});


// 存档选中的人员的map数组
const defaultProps = {
  children: "children",
  label: "deptName",
};
const queryParams = ref<UserReq>({
  curPage: 1,
  pageSize: 10,
});
const listLoading: Ref<boolean> = ref(false);
//获取列表的数据
const tableData = ref([] as UserModel[]);
// 总条数
const total: Ref<number> = ref(0);
// 选择的部门v-model 绑定的
const deptSelectModel = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();
// 存放选中的人员数组
const dynamicTags = ref<Map<string, UserModel>>(
  new Map<string, UserModel>(props.userListArr),
);
const rowSelectFlag = ref<boolean>(false);
// 存放选择部门的数据
const deptSelectArr = ref<DeptModel[]>([]);
let tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "sysUser.fullName",
    prop: "realName",
    isColumn: true,
  },
  // 手机号
  {
    label: "sysUser.phoneNumber",
    prop: "mobilePhoneIns",
    isColumn: true,

  },
  // 岗位职务
  {
    label: "sysUser.position",
    prop: "jobName",
    isColumn: true,
  },
]);
// 过滤部门函数
function filterNode(value: string, data: DeptModel) {
  console.log(value, data)
  if (!value) return true;
  return (data.deptName as string).includes(value);
}


// 根据输入框输入的值去查询对应的人员
function filterInputData() {
  getUserList()
}
// 根据左侧部门的id获取人员列表
function getTreeKey(value: DeptTreeSelectModel) {
  queryParams.value.deptId = "";
  // 清除选中人员的复选框焦点
  multipleTableRef.value?.clearSelection();
  if(value.deptId) {
    queryParams.value.deptId = value.deptId;
  }
  // 点击部门后右侧展示部门下的人员
  getUserList()
}


// 行选择
function tableSelected(row: UserModel[]) {
  if (rowSelectFlag.value) return
  const newMap = new Map();
  row.forEach((item) => newMap.set(item.userId, item));
  dynamicTags.value.forEach((key: UserModel) => {
    if (!newMap.has(key)) newMap.delete(key);
  });
  console.log(newMap)
  dynamicTags.value = newMap;
}

function getTagLabel(tag: UserModel) {
  return tag.realName;
}

// 清除部门选择后列表为空
function deptSelectClear() {
  queryParams.value.deptId = "";
  tableData.value = [];
}

function handleDynamicTags() {
  if (dynamicTags.value && multipleTableRef.value) {
    setTimeout(() => {
    rowSelectFlag.value = true;
    tableData.value.forEach((item: UserModel) => {
      const isSelected = dynamicTags.value.has(item.userId as string);
      multipleTableRef.value?.toggleRowSelection(item, isSelected);
    });
    rowSelectFlag.value = false;
  }, 0);
  }
}

// 获取人员列表
function getUserList() {
  console.log(dynamicTags.value)
  listLoading.value = true;
  userApi.findPage(queryParams.value).then(({ data }) => {
    tableData.value = data.results;
    total.value = data.totalSize;
    listLoading.value = false;
    handleDynamicTags();
  })
}

// 根据输入的部门名称进行过滤对应部门
function filterDept(value: string) {
  treeRef.value!.filter(value);
}

onBeforeMount(() => {
  // 将部门数据获取到
  deptApi.findList().then(({ data }) => {
    deptSelectArr.value = data.results;
  });
  getUserList();
  if (props.userId && props.userId.length > 0) {
    props.userId.forEach((item: any) => {
      // 根据每一个用户id去查询对应的信息
      userLogUser(item).then(({ data }) => {
        console.log(data)
        // 根据对应的信息塞到已选中的人,数组中s
        // 存入到tag中
        data.key = data.userId;
        data.value = data.realName;
        dynamicTags.value.set(data.userId as string, data);
      });
    });
  }
});
defineExpose({
  dynamicTags: dynamicTags
})

</script>
<style scoped lang="scss">
.dept-people-select-left-box {
  border-right: 1px solid #dcdfe6;
  min-height: 450px;
  max-height: 700px;
}
.dept-people-select-main {
  max-height: 700px;
}
.dept-people-select-table {
  min-height: 450px;
  max-height: 700px;
}
.dept-people-select-overflow {
  overflow: auto;
  scrollbar-width: none; /* Firefox 64+ */
  -ms-overflow-style: none; /* IE and Edge */
  overflow-y: scroll; /* 添加滚动条 */
}

.dept-people-select-tag-box {
  display: flex;
  align-items: center;
  min-height: 40px;
  padding: 3px 6px;
  border: 1px solid #dcdcdc;
  margin: 10px 0;
}
.dept-people-select-font-size {
  font-size: 15px;
  font-weight: 700;
  margin-bottom: 10px;
}
.dept-people-select-tag-item {
  margin-right: 5px;
}

.table-top {
  margin-top: 10px;
}
</style>
